import * as http from 'http';
import * as url from 'url';
import { toolDefinitions, toolImplementations } from './tools';
import { MCP_SERVER_PORT } from "./config";

/**
 * MCP Server - 独立的工具服务
 * 不依赖任何AI框架，纯HTTP服务
 */
export class MCPServer {
    private server: http.Server;

    constructor() {
        this.server = this.createHTTPServer();
    }

    private createHTTPServer(): http.Server {
        return http.createServer(async (req, res) => {
            // Enable CORS
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
            res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
            res.setHeader('Content-Type', 'application/json');

            if (req.method === 'OPTIONS') {
                res.writeHead(200);
                res.end();
                return;
            }

            try {
                const parsedUrl = url.parse(req.url!, true);

                if (req.method === 'GET' && parsedUrl.pathname === '/tools') {
                    // Get available tools
                    res.writeHead(200);
                    res.end(JSON.stringify({
                        success: true,
                        tools: this.getTools()
                    }));

                } else if (req.method === 'POST' && parsedUrl.pathname === '/execute') {
                    // Execute tool
                    let body = '';
                    req.on('data', chunk => {
                        body += chunk.toString();
                    });

                    req.on('end', async () => {
                        try {
                            const { toolName, args } = JSON.parse(body);
                            const result = await this.executeTool(toolName, args);
                            res.writeHead(200);
                            res.end(JSON.stringify({
                                success: true,
                                result: result
                            }));
                        } catch (error) {
                            res.writeHead(400);
                            res.end(JSON.stringify({
                                success: false,
                                error: error instanceof Error ? error.message : 'Unknown error'
                            }));
                        }
                    });

                } else {
                    res.writeHead(404);
                    res.end(JSON.stringify({
                        success: false,
                        error: 'Not found'
                    }));
                }

            } catch (error) {
                res.writeHead(500);
                res.end(JSON.stringify({
                    success: false,
                    error: error instanceof Error ? error.message : 'Internal server error'
                }));
            }
        });
    }

    /**
     * 获取可用工具列表
     * 返回工具名称、描述和JSON Schema
     */
    public getTools() {
        return Object.entries(toolDefinitions).map(([name, definition]) => ({
            name,
            description: definition.description,
            schemaDescription: definition.schema
        }));
    }

    /**
     * 执行指定的工具
     */
    public async executeTool(toolName: string, args: any): Promise<any> {
        const toolImpl = toolImplementations[toolName];
        if (!toolImpl) {
            throw new Error(`Tool ${toolName} not found`);
        }

        const toolDef = toolDefinitions[toolName];
        if (!toolDef) {
            throw new Error(`Tool definition for ${toolName} not found`);
        }

        console.log(`[MCP Server] Executing tool: ${toolName}`);
        console.log(`[MCP Server] Args:`, args);

        const result = await toolImpl(args);

        let logResult = result;
        if (toolName === 'api-doc-search') {
            logResult = `已查询到记录${Array.isArray(result) ? result.length : 0}条`;
        }
        console.log(`[MCP Server] Tool result:`, logResult);

        return result;
    }

    /**
     * 检查工具是否存在
     */
    public hasTool(toolName: string): boolean {
        return toolName in toolDefinitions && toolName in toolImplementations;
    }

    /**
     * 启动MCP Server HTTP服务
     */
    public start(): void {
        this.server.listen(MCP_SERVER_PORT, () => {
            console.log(`[MCP Server] HTTP service started on port ${MCP_SERVER_PORT}`);
            console.log(`[MCP Server] Available endpoints:`);
            console.log(`  GET  http://localhost:${MCP_SERVER_PORT}/tools`);
            console.log(`  POST http://localhost:${MCP_SERVER_PORT}/execute`);
            console.log(`[MCP Server] Available tools:`, Object.keys(toolDefinitions));
        });
    }

    /**
     * 停止MCP Server
     */
    public stop(): void {
        this.server.close();
    }
}